<template>
  <div>
    <van-nav-bar title="登录" />
    <van-form @submit="onSubmit" autocomplete="off">
      <van-field
        v-model="username"
        name="username"
        label="用户名"
        placeholder="用户名"
        :rules="[
          { required: true, message: '请填写用户名' },
          { pattern: /^[\w-]{4,16}$/, message: '请输入4-6位数' },
        ]"
      />
      <van-field
        v-model="password"
        type="password"
        name="password"
        label="密码"
        placeholder="密码"
        :rules="[
          { required: true, message: '请填写密码' },
          { pattern: /^[\w-]{8,16}$/, message: '请填写8-16位密码' },
        ]"
      />
      <div style="margin: 16px">
        <van-button  block type="info" native-type="submit"
          >登录</van-button
        >
      </div>
      <router-link class="link" to="/register">没有账号，去注册</router-link>
    </van-form>
  </div>
</template>

<script>
import { login } from '../api/users'
import { setToken } from '../utils/storage'
export default {
  name: 'LoginPage',
  data () {
    return {
      username: '',
      password: ''
    }
  },
  methods: {
    async onSubmit (values) {
      this.$toast.loading({
        message: '疯狂登录中...',
        forbidClick: true
      })
      const { data } = await login(values)
      // 储存Token到本地
      setToken(data.data.token)
      // 登录成功提示
      this.$toast('登录成功')
      // 跳转到首页
      this.$router.push('/article')
    }
  }
}
</script>

<style>
.link {
  color: #07c160;
  font-size: 12px;
  float: right;
  padding-right: 20px;
}
</style>
